package com.mgkj.controller.WMS;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.mgkj.annotation.Log;
import com.mgkj.common.result.Result;
import com.mgkj.dto.*;
import com.mgkj.entity.InvBarcodeOperation;
import com.mgkj.entity.InvBarcodeTransaction;
import com.mgkj.mapper.PassiveMapper;
import com.mgkj.service.InvBarcodeOperationService;
import com.mgkj.service.InvBarcodeTransactionService;
import com.mgkj.service.PassiveService;
import com.mgkj.vo.BarCodeDetailVo;
import com.mgkj.vo.InvBarcodeOperationVo;
import com.mgkj.vo.PassiveEmployeeInfoVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.UUID;

/**
 * @author yyyjcg
 * @date 2023/12/26
 * @Description
 */
@Slf4j
@RestController
@Api(tags = "ABL无源管理相关接口")
@RequestMapping("/ABLPassive")
public class ABLPassiveController {

    @Autowired
    private PassiveService passiveService;

    @Autowired
    private PassiveMapper passiveMapper;

    @Resource
    private InvBarcodeOperationService invBarcodeOperationService;

    @Resource
    private InvBarcodeTransactionService invBarcodeTransactionService;

    @ApiOperation("查询无源调拨箱码信息")
    @PostMapping("/getTransferBarcodeInfo")
    @DSTransactional
    public Result getTransferBarcodeInfo (@RequestBody PassiveTransferBarcodeDto dto) {

        // 1.查询条码详情
        BarCodeDetailVo barCodeDetail = passiveMapper.getBarCodeDetailByBarCode(dto.getBarcode());
        if (barCodeDetail == null) {
            return Result.fail().message("条码不存在");
        }

        return Result.ok(barCodeDetail);

    }



    @PostMapping("/saveTransferBarcodeInfo")
    @ApiOperation(value = "扫码匹配并保存需调拨数据")
    @DSTransactional
    public Result<?> saveTransferBarcodeInfo(@RequestBody PassiveInvBarcodeOperationDto dto) {
        // 1.查询该条码操作档 汇总数量
        Double qtySum = passiveMapper.getQtySum(dto.getBarcode(),dto.getChagType());
        if (qtySum == null) {
            qtySum = 0.0;
        }

        double remainingQty = dto.getMatchQty() - qtySum;
        if (remainingQty <= 0) {
            return Result.fail().message("条码剩余数量不足");
        }

        InvBarcodeOperation invBarcodeOperation = new InvBarcodeOperation();
        invBarcodeOperation.setId(UUID.randomUUID().toString()); // UUID
        invBarcodeOperation.setBarcode(dto.getBarcode()); // 条码编号
        invBarcodeOperation.setQty(BigDecimal.valueOf(dto.getMatchQty())); // 条码数量
        invBarcodeOperation.setSnFromWarehouseNo(dto.getFromWarehouseCode()); // 调出仓库编号
        invBarcodeOperation.setSnFromCellNo(dto.getFromBinCode()); // 调出库位编号
        invBarcodeOperation.setSnToWarehouseNo(dto.getToWarehouseCode()); // 调入库位编号
        invBarcodeOperation.setSnToCellNo(dto.getToBinCode()); // 调入库位编号
        invBarcodeOperation.setItemNo(dto.getItemCode()); // 品号
        invBarcodeOperation.setItemName(dto.getItemName()); // 品名
        invBarcodeOperation.setItemSpec(dto.getItemSpec()); // 规格
        invBarcodeOperation.setUnitNo(dto.getUnitCode()); // 单位编号
        invBarcodeOperation.setUnitName(dto.getUnitName()); // 单位编号
        invBarcodeOperation.setChagType(5); // 5:无源调拨
        invBarcodeOperation.setStatusCode(0); // 0:未提交 1:已提交
        invBarcodeOperation.setCreateDate(DateTime.now().toString()); // 创建时间
        invBarcodeOperation.setCreateBy(dto.getCreateBy()); // 操作人
        invBarcodeOperation.setRemark(dto.getRemark()); // 备注
        invBarcodeOperation.setOrgNo(dto.getShjg()); // 备注
        boolean b = invBarcodeOperationService.save(invBarcodeOperation);
        if (!b) {
            return Result.fail().message("操作记录保存失败");
        }
        return Result.ok(invBarcodeOperation).message("操作记录保存成功");

     }

    @PostMapping("/getInvBarcodeOperation")
    @ApiOperation(value = "获取已扫描条码操作档记录-无源调拨")
    public Result<List<InvBarcodeOperationVo>> getInvBarcodeOperation(@RequestBody String createBy) {
        List<InvBarcodeOperationVo> InvBarcodeOperationList = passiveMapper.queryInvBarcodeOperationVo(createBy);
        return Result.ok(InvBarcodeOperationList);
    }


    @PostMapping("/deleteScanResult")
    @ApiOperation(value = "删除扫码结果列表")
    @Transactional
    public Result<?> deleteScanResult(@RequestBody QueryPassiveDTO dto) {
        passiveMapper.deleteInvBarcodeOperationByCreateBy(dto.getCreateBy(),dto.getChagType());
        return Result.ok();
    }

    @ApiOperation("无源调拨-提交")
    @PostMapping("/TransferDocSubmit")
    @Log("无源调拨-提交")
    public Result PassiveTransferDocSubmit(@RequestBody PassiveTransferSubmitDto dto ) {

        //1、提交e10
        //同步中间表
        MiddleReturnDto middleReturnDto = passiveService.ABLPassiveTransferInsertMiddleTable(dto.getList());
        //提交e10
        JSONObject jsonObject = passiveService.PassiveTransferSubmit(middleReturnDto);
        String executionCode = jsonObject
                .getJSONObject("payload")
                .getJSONObject("std_data")
                .getJSONObject("execution")
                .getString("code");

        System.out.println(jsonObject);
        if (!"0".equals(executionCode)) {
            return Result.fail(jsonObject);
        }
            for(PassiveTransferDocSubmitDto list :dto.getList()){
            // 1.查询未提交标签
            List<InvBarcodeOperation> operationList = passiveMapper.queryTransNotSubimtByTypeAndCreateBy(5, dto.getCreateBy(),list.getBarcode());
            for (InvBarcodeOperation invBarcodeOperation : operationList) {
                // 2.更新状态为已提交
                passiveMapper.updateByid(invBarcodeOperation.getId());
                // 3.扣减条码的剩余数量
                passiveMapper.updateBmBarcodeDetailOfQty(invBarcodeOperation.getBarcode(), invBarcodeOperation.getQty().doubleValue());
                // 4.保存条码结果档
                InvBarcodeTransaction invBarcodeTransaction = new InvBarcodeTransaction();
                invBarcodeTransaction.setBarcode(invBarcodeOperation.getBarcode());
                invBarcodeTransaction.setItemNo(invBarcodeOperation.getItemNo());
                invBarcodeTransaction.setItemName(invBarcodeOperation.getItemName());
                invBarcodeTransaction.setItemSpec(invBarcodeOperation.getItemSpec());
                invBarcodeTransaction.setQty(invBarcodeOperation.getQty());
                invBarcodeTransaction.setReferenceQty(invBarcodeOperation.getReferenceQty());
                invBarcodeTransaction.setWarehouseNo(invBarcodeOperation.getSnFromWarehouseNo());
                invBarcodeTransaction.setCellNo(invBarcodeOperation.getSnFromCellNo());
                invBarcodeTransaction.setSnFromWarehouseNo(invBarcodeOperation.getSnFromWarehouseNo());
                invBarcodeTransaction.setSnFromCellNo(invBarcodeOperation.getSnFromCellNo());
                invBarcodeTransaction.setSnToWarehouseNo(invBarcodeOperation.getSnToWarehouseNo());
                invBarcodeTransaction.setSnToCellNo(invBarcodeOperation.getSnToCellNo());
                invBarcodeTransaction.setUnitNo(invBarcodeOperation.getUnitNo());
                invBarcodeTransaction.setUnitName(invBarcodeOperation.getUnitName());
                invBarcodeTransaction.setChagType(invBarcodeOperation.getChagType());
                invBarcodeTransaction.setStatusCode(invBarcodeOperation.getStatusCode());
                invBarcodeTransaction.setCreateBy(invBarcodeOperation.getCreateBy());
                invBarcodeTransaction.setDocReturnFlag(invBarcodeOperation.getDocReturnFlag());
                invBarcodeTransaction.setStockKeep(invBarcodeOperation.getStockKeep());
                invBarcodeTransaction.setStockRate(invBarcodeOperation.getStockRate());
                invBarcodeTransactionService.save(invBarcodeTransaction);

            }
        }


            return Result.ok(jsonObject);
        }



    @ApiOperation("查询无源出入库员工部门信息")
    @PostMapping("/getEmployeeInfo")
    public Result<List<PassiveEmployeeInfoVo>> getEmployeeInfo (@RequestBody PassiveEmployeeInfoDto dto) {
        Result<List<PassiveEmployeeInfoVo>> list = passiveService.getEmployeeInfo(dto);
        return list;

    }




    @ApiOperation("查询无源出入库箱码信息")
    @PostMapping("/getToOrOutBarcodeInfo")
    @DSTransactional
    public Result getToOrOutBarcodeInfo (@RequestBody PassiveToOrOutBarcodeDto dto) {
        // 1.查询条码详情
        BarCodeDetailVo barCodeDetail = passiveMapper.getBarCodeDetailByBarCode(dto.getBarcode());
        if (barCodeDetail == null) {
            return Result.fail().message("条码不存在");
        }
        return Result.ok(barCodeDetail);
    }

    @PostMapping("/saveToOrOutBarcodeInfo")
    @ApiOperation(value = "保存需出入库数据")
    @DSTransactional
    public Result<?> saveToOrOutBarcodeInfo(@RequestBody PassiveToOrOutInvBarcodeOperationDto dto) {
        // 1.查询该条码操作档 汇总数量
        Double qtySum = passiveMapper.getQtySum(dto.getBarcode(),dto.getChagType());
        if (qtySum == null) {
            qtySum = 0.0;
        }

        double remainingQty = dto.getMatchQty() - qtySum;
        if (remainingQty <= 0) {
            return Result.fail().message("条码剩余数量不足");
        }

        InvBarcodeOperation invBarcodeOperation = new InvBarcodeOperation();
        invBarcodeOperation.setId(UUID.randomUUID().toString()); // UUID
        invBarcodeOperation.setBarcode(dto.getBarcode()); // 条码编号
        invBarcodeOperation.setQty(BigDecimal.valueOf(dto.getMatchQty())); // 条码数量
        invBarcodeOperation.setWarehouseNo(dto.getWarehouseCode()); // 仓库编号
        invBarcodeOperation.setCellNo(dto.getBinCode()); // 库位编号
        invBarcodeOperation.setItemNo(dto.getItemCode()); // 品号
        invBarcodeOperation.setItemName(dto.getItemName()); // 品名
        invBarcodeOperation.setItemSpec(dto.getItemSpec()); // 规格
        invBarcodeOperation.setUnitNo(dto.getUnitCode()); // 单位编号
        invBarcodeOperation.setUnitName(dto.getUnitName()); // 单位编号
        invBarcodeOperation.setChagType(dto.getChagType()); // 5无源调拨、6无源入库、7无源出库
        invBarcodeOperation.setStatusCode(0); // 0:未提交 1:已提交
        invBarcodeOperation.setCreateDate(DateTime.now().toString()); // 创建时间
        invBarcodeOperation.setCreateBy(dto.getCreateBy()); // 操作人
        invBarcodeOperation.setRemark(dto.getRemark()); // 备注
        invBarcodeOperation.setOrgNo(dto.getShjg()); // 备注
        invBarcodeOperation.setLotAtt01(dto.getEmployeeCode()); // 人员编号
        invBarcodeOperation.setLotAtt02(dto.getDepartmentCode()); // 部门编号
        invBarcodeOperation.setLotAtt03(dto.getDepartmentName()); // 部门名称

        boolean b = invBarcodeOperationService.save(invBarcodeOperation);
        if (!b) {
            return Result.fail().message("操作记录保存失败");
        }
        return Result.ok(invBarcodeOperation).message("操作记录保存成功");

    }

    @PostMapping("/getToOrOutInvBarcodeOperation")
    @ApiOperation(value = "获取已扫描条码操作档记录-无源出入库")
    public Result<List<InvBarcodeOperationVo>> getToOrOutInvBarcodeOperation(GetToOrOutInvBarcodeOperationDto dto) {
        List<InvBarcodeOperationVo> InvBarcodeOperationList = passiveMapper.queryToOrOutInvBarcodeOperationVo(dto.getCreateBy(), dto.getChagType());
        return Result.ok(InvBarcodeOperationList);
    }



    @ApiOperation("无源入库/杂收-提交")
    @PostMapping("/PassiveToStorageGenerateDoc")
    public Result PassiveToStorageGenerateDoc(@RequestBody PassiveToSubmitDto dto) {
            //1、提交e10
            //同步中间表
            MiddleReturnDto middleReturnDto = passiveService.ABLPassiveToStorageInsertMiddleTable(dto.getList());
            //提交e10
            JSONObject jsonObject = passiveService.PassiveToStorageSubmit(middleReturnDto);
        String executionCode = jsonObject
                .getJSONObject("payload")
                .getJSONObject("std_data")
                .getJSONObject("execution")
                .getString("code");

        System.out.println(jsonObject);
        if (!"0".equals(executionCode)) {
            return Result.fail(jsonObject);
        }

        // 1.查询未提交标签
        List<InvBarcodeOperation> operationList = passiveMapper.queryNotSubimtByTypeAndCreateBy(6, dto.getCreateBy());
        for (InvBarcodeOperation invBarcodeOperation : operationList) {
            // 2.更新状态为已提交
            passiveMapper.updateByid(invBarcodeOperation.getId());
//            passiveMapper.updateByid(invBarcodeOperation.getId());
            // 3.扣减条码的剩余数量-杂收不应该扣条码数量
//            passiveMapper.updateBmBarcodeDetailOfQty(invBarcodeOperation.getBarcode(), invBarcodeOperation.getQty().doubleValue());
            // 4.保存条码结果档
            InvBarcodeTransaction invBarcodeTransaction = new InvBarcodeTransaction();
            invBarcodeTransaction.setBarcode(invBarcodeOperation.getBarcode());
            invBarcodeTransaction.setQty(invBarcodeOperation.getQty());
            invBarcodeTransaction.setItemNo(invBarcodeOperation.getItemNo());
            invBarcodeTransaction.setItemName(invBarcodeOperation.getItemName());
            invBarcodeTransaction.setItemSpec(invBarcodeOperation.getItemSpec());
            invBarcodeTransaction.setWarehouseNo(invBarcodeOperation.getWarehouseNo());
            invBarcodeTransaction.setCellNo(invBarcodeOperation.getCellNo());
            invBarcodeTransaction.setUnitNo(invBarcodeOperation.getUnitNo());
            invBarcodeTransaction.setUnitName(invBarcodeOperation.getUnitName());
            invBarcodeTransaction.setReferenceQty(invBarcodeOperation.getReferenceQty());
            invBarcodeTransaction.setChagType(invBarcodeOperation.getChagType());
            invBarcodeTransaction.setDocReturnFlag(invBarcodeOperation.getDocReturnFlag());
            invBarcodeTransaction.setStatusCode(invBarcodeOperation.getStatusCode());
            invBarcodeTransaction.setStockRate(invBarcodeOperation.getStockRate());
            invBarcodeTransaction.setStockKeep(invBarcodeOperation.getStockKeep());
            invBarcodeTransaction.setCreateBy(invBarcodeOperation.getCreateBy());
            invBarcodeTransactionService.save(invBarcodeTransaction);
        }



        return Result.ok(jsonObject);

    }


    @ApiOperation("无源出库/杂发-提交")
    @PostMapping("/PassiveOutStorageGenerateDoc")
    public Result PassiveOutStorageGenerateDoc(@RequestBody PassiveOutSubmitDto dto) {
            //1、提交e10
            //同步中间表
            MiddleReturnDto middleReturnDto = passiveService.ABLPassiveOutStorageInsertMiddleTable(dto.getList());
            //提交e10
            JSONObject jsonObject = passiveService.PassiveOutStorageSubmit(middleReturnDto);
            System.out.println(jsonObject.toJSONString());
        String executionCode = jsonObject
                .getJSONObject("payload")
                .getJSONObject("std_data")
                .getJSONObject("execution")
                .getString("code");

        System.out.println(jsonObject);
        if (!"0".equals(executionCode)) {
            return Result.fail(jsonObject);
        }

        // 1.查询未提交标签
        List<InvBarcodeOperation> operationList = passiveMapper.queryNotSubimtByTypeAndCreateBy(7, dto.getCreateBy());
        for (InvBarcodeOperation invBarcodeOperation : operationList) {
            // 2.更新状态为已提交
            passiveMapper.updateByid(invBarcodeOperation.getId());
            // 3.扣减条码的剩余数量
            passiveMapper.updateBmBarcodeDetailOfQty(invBarcodeOperation.getBarcode(), invBarcodeOperation.getQty().doubleValue());
            // 4.保存条码结果档
            InvBarcodeTransaction invBarcodeTransaction = new InvBarcodeTransaction();
            invBarcodeTransaction.setBarcode(invBarcodeOperation.getBarcode());
            invBarcodeTransaction.setQty(invBarcodeOperation.getQty());
            invBarcodeTransaction.setItemNo(invBarcodeOperation.getItemNo());
            invBarcodeTransaction.setItemName(invBarcodeOperation.getItemName());
            invBarcodeTransaction.setItemSpec(invBarcodeOperation.getItemSpec());
            invBarcodeTransaction.setWarehouseNo(invBarcodeOperation.getWarehouseNo());
            invBarcodeTransaction.setCellNo(invBarcodeOperation.getCellNo());
            invBarcodeTransaction.setUnitNo(invBarcodeOperation.getUnitNo());
            invBarcodeTransaction.setUnitName(invBarcodeOperation.getUnitName());
            invBarcodeTransaction.setReferenceQty(invBarcodeOperation.getReferenceQty());
            invBarcodeTransaction.setChagType(invBarcodeOperation.getChagType());
            invBarcodeTransaction.setDocReturnFlag(invBarcodeOperation.getDocReturnFlag());
            invBarcodeTransaction.setStatusCode(invBarcodeOperation.getStatusCode());
            invBarcodeTransaction.setStockRate(invBarcodeOperation.getStockRate());
            invBarcodeTransaction.setStockKeep(invBarcodeOperation.getStockKeep());
            invBarcodeTransaction.setCreateBy(invBarcodeOperation.getCreateBy());
            invBarcodeTransactionService.save(invBarcodeTransaction);
        }

        return Result.ok(jsonObject);
    }









    }

